package com.jbh.recordapp;

import androidx.appcompat.app.AppCompatActivity;
import android.Manifest;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.ViewGroup;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.jbh.recordlibrary.i.AddAudioRecordListener;
import com.jbh.recordlibrary.i.CallBack;
import com.jbh.recordlibrary.i.PlayerWavListener;
import com.jbh.recordlibrary.m.AudioRecordManager;
import com.jbh.recordlibrary.m.MediaPlayerWavManager;
import com.jbh.recordlibrary.u.LogUtil;
import com.jbh.recordlibrary.u.PermissionUtil;
import com.jbh.recordlibrary.u.Utils;
import com.jbh.recordlibrary.v.RecordSliderWaveBitmapView;
import com.jbh.recordlibrary.v.RecordTimeView;
import com.jbh.recordlibrary.v.RecordWaveCutView;
import com.jbh.recordlibrary.v.RecordWaveSurfaceView;
import com.jbh.recordlibrary.v.RecordWaveView;
import org.json.JSONException;
import java.util.ArrayList;
import java.util.List;


public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private RecordWaveSurfaceView mWaveCanvasView;
    private RecordWaveView mRecordWaveView;
    private RecordTimeView mRecordTimeView;
    private RecordWaveCutView mRecordWaveCutView;
    private RecordSliderWaveBitmapView mRecordSliderWaveBitmapView ;

    private TextView tv_time ;
    private ImageView im_wave;

    private HorizontalScrollView mHorizontalScrollView;
    private View lay_waveCanvasView ;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
    }



    private void initView() {
        im_wave = findViewById(R.id.im_wave);
        tv_time = findViewById(R.id.tv_time);
        mHorizontalScrollView = findViewById(R.id.mHorizontalScrollView);
        lay_waveCanvasView = findViewById(R.id.lay_waveCanvasView);
        mWaveCanvasView = findViewById(R.id.mWaveCanvasView);
        mRecordTimeView = findViewById(R.id.mRecordTimeView);
        mRecordWaveView = findViewById(R.id.mRecordWaveView);
        mRecordWaveCutView = findViewById(R.id.mRecordWaveCutView);
        mRecordWaveCutView.setAddAudioRecordListener(addAudioRecordListener);
        mRecordSliderWaveBitmapView  = findViewById(R.id.mRecordSliderWaveBitmapView );
        mRecordSliderWaveBitmapView.setAddAudioRecordListener(addAudioRecordListener);
        findViewById(R.id.btn_start).setOnClickListener(this);
        findViewById(R.id.btn_stop).setOnClickListener(this);
        findViewById(R.id.btn_reStart).setOnClickListener(this);
        findViewById(R.id.btn_pause).setOnClickListener(this);
        findViewById(R.id.btn_cut).setOnClickListener(this);
        findViewById(R.id.btn_play).setOnClickListener(this);

        findViewById(R.id.btn_pause_play).setOnClickListener(this);
        findViewById(R.id.btn_restart).setOnClickListener(this);

        initConfig();
    }


    private void initConfig() {
        /**配置录音绘制图形配置*/
        AudioRecordManager.getInstance().addAudioRecordListener(addAudioRecordListener);
        MediaPlayerWavManager.getInstance().setPlayerWavListener(playerWavListener);
        System.out.println(Environment.getExternalStorageDirectory().getPath());
        System.out.println(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES));
        System.out.println(getExternalCacheDir().toString()); //这个地方不会报错了
        System.out.println(getExternalFilesDir(null).toString());  //这个地方不会报错了
    }


    @Override
    protected void onPause() {
        super.onPause();
        if (AudioRecordManager.getInstance().isRecording){
            AudioRecordManager.getInstance().pause();
        }
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.btn_start:
                List<String> list = new ArrayList<>();
                list.add(Manifest.permission.RECORD_AUDIO);
                list.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
                PermissionUtil.checkPermission(this, list, new PermissionUtil.CheckPermissionListener() {
                    @Override
                    public void startRequestPermission() {
                    }
                    @Override
                    public void noNeedRequestPermission() {
                        if (!AudioRecordManager.getInstance().isRecording){
                            AudioRecordManager.getInstance().start(MainActivity.this);
                        }else {
                            Toast.makeText(MainActivity.this,"正在录音中....",Toast.LENGTH_LONG).show();
                        }
                    }
                });
                break;
            case R.id.btn_stop:
                AudioRecordManager.getInstance().stop();
                break;

            case R.id.btn_reStart:
                if (AudioRecordManager.getInstance().isPause){
                    AudioRecordManager.getInstance().reStart();
                }
                break;

            case R.id.btn_pause:
                if (AudioRecordManager.getInstance().isRecording){
                    AudioRecordManager.getInstance().pause();
                }
                break;

            case R.id.btn_cut:
                cutFileTask();
                break;


                /*播放音频*/
            case R.id.btn_play:
                MediaPlayerWavManager.getInstance().start(recordFilePath);
                break;

            case R.id.btn_pause_play:
                MediaPlayerWavManager.getInstance().pausePlay();
                break;

            case R.id.btn_restart:
                MediaPlayerWavManager.getInstance().reStart();
                break;
        }
    }


    /**
     * 音频文件
     *
     */
    String recordFilePath ;



    /**
     * 截取文件
     */
    private void cutFileTask() {
        mRecordWaveCutView.cutFileTask(new CallBack<String>() {
            @Override
            public void success(String s) {
                recordFilePath = s;
                Toast.makeText(MainActivity.this,"截取成功！\n"+s,Toast.LENGTH_LONG).show();
            }

            @Override
            public void error(String error) {
                Toast.makeText(MainActivity.this,error,Toast.LENGTH_LONG).show();
            }
        });
    }


    private PlayerWavListener playerWavListener = new PlayerWavListener() {

        @Override
        public void onStartPlay() {
            LogUtil.LOG_V("[PlayerWavListener] - > onStartPlay");
        }

        @Override
        public void onProgress(int currentLength, int totalLength) {
            LogUtil.LOG_V("[PlayerWavListener] - > onProgress  currentLength = "+ currentLength +",totalLength = "+totalLength+",time = "+ Utils.formatSecond1(currentLength));
        }

        @Override
        public void onPausePlay(int currentLength) {

        }

        @Override
        public void onStopPlay() {
            LogUtil.LOG_V("[PlayerWavListener] - > onStopPlay");
        }
    };



    private AddAudioRecordListener addAudioRecordListener =new AddAudioRecordListener() {


        @Override
        public void start() {
            mHorizontalScrollView.setVisibility(View.GONE);
            lay_waveCanvasView.setVisibility(View.VISIBLE);
        }


        @Override
        public void reStart() {
            mHorizontalScrollView.setVisibility(View.GONE);
            lay_waveCanvasView.setVisibility(View.VISIBLE);
        }



        @Override
        public void pause() {
            mHorizontalScrollView.setVisibility(View.VISIBLE);
            mHorizontalScrollView.scrollTo(mRecordWaveView.getMeasuredWidth(),0);
            lay_waveCanvasView.setVisibility(View.GONE);
        }



        /**
         * 录制完成
         *
         * @param wavFile
         */
        @Override
        public void stop(String wavFile) {
            mHorizontalScrollView.setVisibility(View.GONE);
            mWaveCanvasView.setVisibility(View.VISIBLE);
        }



        /**
         * 绘制的宽度
         *
         * @return
         */
        @Override
        public int getDrawWaveWidth() {
            return mWaveCanvasView.getMeasuredWidth();
        }



        /**
         * 实时绘制
         *
         * 正在录音中
         *
         * @param divider
         * @param buf
         */
        @Override
        public void recordBuffer(float divider, ArrayList<Short> buf) {
            try {
                mWaveCanvasView.drawRecord(divider,buf);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }


        /**
         * 暂时实时录音时间
         *
         * @param t
         */
        @Override
        public void recordCurrentTime(long t) {
            tv_time.setText(Utils.formatSecond((int) t));
        }


        /**
         * 录音暂停  汇总信息
         * 或者停止  之后的信息
         *
         * @param divider
         * @param oneSecondLength 每一面绘制长度
         * @param totalBuf  总绘制声波的数据
         * @param totalTime 录音的总时间
         * @param totalLength 录音绘制声波图的总长度 px
         * @param recordFilePath 录音文件路径
         *
         */
        @Override
        public void totalRecord(float divider,
                                float oneSecondLength,
                                ArrayList<Short> totalBuf,
                                final long totalTime,
                                float totalLength,
                                String recordFilePath) {

            ViewGroup.LayoutParams params = mRecordWaveView.getLayoutParams();
            params.width = (int) (totalLength + 2);
            mRecordWaveView.setLayoutParams(params);
            mRecordWaveView.setData(divider,totalBuf);
            mRecordTimeView.setData(oneSecondLength,totalTime);

            mRecordWaveCutView.setRecordData(
                    divider,
                    oneSecondLength,
                    totalBuf,
                    totalTime,
                    totalLength+2,
                    recordFilePath);

            MainActivity.this.recordFilePath = recordFilePath;
        }



        /**
         * 截取成为新的wav音频文件
         *
         * @param divider
         * @param oneSecondLength 每一面绘制长度
         * @param totalLength 截取后声波图的总长度 px
         * @param totalBuf 截取后声波的数据
         * @param totalTime 截取后的时间
         */
        @Override
        public void onCutRecord(float divider,
                                float oneSecondLength,
                                float totalLength,
                                List<Short> totalBuf,
                                float totalTime) {
            mRecordSliderWaveBitmapView.setRecordData(
                    divider,
                    oneSecondLength,
                    totalBuf,
                    (long) (totalTime*1000),
                    totalLength);
        }



        /***
         * 将某一段的声波转成bitmap位图
         *
         * @param b
         */
        @Override
        public void onWaveBitmap(Bitmap b) {
            if (b!=null){
                im_wave.setImageBitmap(b);
            }
        }
    };
}